import re
import os
import sys
import urllib
import logging

from google.appengine.api import users
from google.appengine.ext import db

import webapp2
import jinja2

from glog.template.Environment import tpltenv

import Error
from glog import AppEnv
from glog.models import AppConfig
from glog.models import Theme
from glog.models import Blog

class RequestHandler(webapp2.RequestHandler):
    def initialize(self, request, response):
        webapp2.RequestHandler.initialize(self, request, response)

        self.reqpath = self.request.path[len(AppEnv.apppath):]
        self.user = users.get_current_user()
        self.is_admin = users.is_current_user_admin()
        self.is_blogger = False
        if self.user:
            self.is_blogger = Blog.is_blogger(self.user.email())
            
        try:
            self.referer = self.request.headers['referer']
        except:
            self.referer = None

        self.appconfig = AppConfig.getAppConfig()
        self.appname = AppEnv.appname
        self.appversion = AppEnv.appversion
        self.apppath = AppEnv.apppath
        
        self.templatedic = {
                     'appname': self.appname,
                     'appversion': self.appversion,
                     'apppath': self.apppath,
                     'appconfig': self.appconfig,
                     'user': self.user,
                     'is_admin': self.is_admin,
                     'is_blogger': self.is_blogger,
                     'referer': self.referer,
                     }

    def param(self, name, **kw):
        tmp = self.request.get(name, **kw)
        if isinstance(tmp, unicode):
            tmp = tmp.encode(AppEnv.appencoding)
        return tmp

    def write(self, s):
        self.response.out.write(s)

    def render(self, pageid, default=False):
        default_path = 'default' + '/' + pageid
        if default or not hasattr(self, 'theme') or not self.theme:
            # if theme not set, use default theme
            self.templatedic['theme'] = Theme.getDefaultTheme()
            path = default_path
        else:
            path = self.theme.name + '/' + pageid
        try:
            template = tpltenv.get_template(path)
        except jinja2.TemplateNotFound:
            template = tpltenv.get_template(default_path)
        
        self.write(template.render(self.templatedic))

    def renderErrorPage(self,msg=None,statecode=None,url=None):
        self.templatedic['errmsg'] = str(msg)
        if statecode:
            self.error(statecode)
        if not url:
            if self.referer:
                url = self.referer
            else:
                url = AppEnv.apppath
        self.templatedic['url'] = url
        self.render(Theme.ShowError_page)

class PageRequestHandler(RequestHandler):
    def handle_exception(self, exception, debug_mode):
        if isinstance(exception, Error.NoPrivilegeError):
            self.redirect(users.create_logout_url(users.create_login_url(urllib.unquote_plus(self.request.uri))))
            return
        if isinstance(exception, Error.PageNotFoundError)\
           or isinstance(exception, Error.NoThisObjectError):
            self.renderErrorPage(msg=str(exception), statecode=404)
            return
        if debug_mode:
            return RequestHandler.handle_exception(self, exception, debug_mode)
        self.renderErrorPage(msg='Server Internal Error\n%s'%str(exception), statecode=500)
    def initialize(self, request, response):
        RequestHandler.initialize(self, request, response)
        # the baseurl is the 
        self.templatedic['baseurl'] = 0
        self.templatedic['userbaseurl'] = 0

        if not self.user:
            login_url = users.create_login_url(urllib.unquote_plus(self.request.uri))
            logout_url = ''
        else:
            login_url = ''
            logout_url = users.create_logout_url(urllib.unquote_plus(self.request.uri))
        self.templatedic['logout_url'] = logout_url
        self.templatedic['login_url'] = login_url
        

    def renderErrorPage(self,msg=None,statecode=None,url=None):
        self.templatedic['errmsg'] = str(msg)
        if statecode:
            self.error(statecode)
        if not url:
            if self.referer:
                url = self.referer
            else:
                url = AppEnv.apppath
        self.templatedic['url'] = url
        self.render(Theme.ShowError_page)

class AjaxRequestHandler(RequestHandler):
    def handle_exception(self, exception, debug_mode):
        if isinstance(exception, Error.PageNotFoundError)\
           or isinstance(exception, Error.NoThisObjectError):
            self.renderErrorPage(msg='Server Internal Error\n%s'%str(exception), statecode=404)
        if debug_mode:
            return super(RequestHandler, self).handle_exception(exception, debug_mode)
        self.renderErrorPage(msg='Server Internal Error\n%s'%str(exception), statecode=500)
        return

    def renderErrorPage(self,msg=None,statecode=None,url=None):
        self.templatedic['errmsg'] = str(msg)
        if statecode:
            self.error(statecode)
        self.write(json.write({'status':False,'errmsg':msg}))
        return
    
class HTTP404(RequestHandler):
    def get(self):
        self.renderErrorPage(Error.PageNotFoundError(),404)
    def post(self):
        return self.get()

class HTTP500(RequestHandler):
    def get(self):
        self.renderErrorPage('Server Intenal Error',500)
    def post(self):
        return self.get()

